package cn.com.java.controller;

import com.alibaba.fastjson2.util.DateUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.UUID;

/**
 * @author liushuntao
 * @date 2024/3/20
 */
@RestController
@RequestMapping("/images")
public class FileUploadController {

    @Value("${spring.servlet.multipart.location}")
    private String uploadPath; // 静态路径配置

    @Value("${target.images}")
    private String targetPath; // 静态路径配置

    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 获取上传文件的原始名称
            String fileName = StringUtils.cleanPath(file.getOriginalFilename());
            // 生成唯一的文件名
            String uniqueFileName = UUID.randomUUID() + fileName;

            // 拼接保存文件的完整路径
            Path targetLocation = Paths.get(uploadPath).resolve(uniqueFileName);
            Path targetPathLocation = Paths.get(targetPath).resolve(uniqueFileName);
            // 将文件保存到指定路径
            Files.copy(file.getInputStream(), targetLocation);
            Files.copy(file.getInputStream(), targetPathLocation);
            // 构建访问URL并返回
            return ServletUriComponentsBuilder.fromCurrentContextPath()
                    .path("/images/")
                    .path(uniqueFileName)
                    .toUriString();
        } catch (Exception e) {
            e.printStackTrace();
            return "上传失败：" + e.getMessage();
        }
    }
}
